from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import Optional
from datetime import datetime
from app.core.auth import get_current_user
from app.db.session import get_db
from app.models.user import User
from app.models.bill import Bill as BillModel
from app.schemas.bill import Bill, BillCreate, BillList, BillStats
from app.core.logging_config import get_logger

logger = get_logger(__name__)
router = APIRouter()

@router.post("/", response_model=Bill)
async def create_bill(
    bill: BillCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """创建账单"""
    try:
        db_bill = BillModel(**bill.dict(), user_id=current_user.id)
        db.add(db_bill)
        db.commit()
        db.refresh(db_bill)
        return db_bill
    except Exception as e:
        logger.error(f"Failed to create bill: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/", response_model=BillList)
async def get_bills(
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
    page: int = 1,
    page_size: int = 20,
    start_date: Optional[datetime] = None,
    end_date: Optional[datetime] = None
):
    """获取账单列表"""
    try:
        skip = (page - 1) * page_size
        query = db.query(BillModel).filter(BillModel.user_id == current_user.id)
        
        if start_date:
            query = query.filter(BillModel.date >= start_date)
        if end_date:
            query = query.filter(BillModel.date <= end_date)
            
        total = query.count()
        bills = query.offset(skip).limit(page_size).all()
        
        return {
            "total": total,
            "list": bills
        }
    except Exception as e:
        logger.error(f"Failed to get bills: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))

@router.delete("/{bill_id}")
async def delete_bill(
    bill_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """删除账单"""
    try:
        bill = db.query(BillModel).filter(
            BillModel.id == bill_id,
            BillModel.user_id == current_user.id
        ).first()
        
        if not bill:
            raise HTTPException(status_code=404, detail="Bill not found")
            
        db.delete(bill)
        db.commit()
        return {"message": "Bill deleted"}
    except Exception as e:
        logger.error(f"Failed to delete bill: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e)) 